package basics.algorithm.sort;

/**
 * 冒泡排序
 * 
 * @author lisy
 */
public class BubbleSort {

	public static void bubbleSort(int[] arr) {
		// 先考虑边界条件
		if (arr == null || arr.length < 2) {
			return;
		}
		int N = arr.length;
		// 范围，两个相邻的交换
		for (int i = N-1; i >= 0; i--) {
			for (int j = 1; j <= N-1; j++) {
				if (arr[j-1] > arr[j]) {
					swap(arr, j-1, j);
				}
			}
		}
	}
	
	public static void swap(int[] arr, int i, int j) {
		int temp = arr[j];
		arr[j] = arr[i];
		arr[i] = temp;
	}
	
	public static void printArray(int[] arr) {
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		int[] arr = {7,1,3,5,8,9,4,6,2};
		printArray(arr);
		bubbleSort(arr);
		printArray(arr);
	}
}
